/**
 * 
 */
package server;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import server.alarmThreads.OnlineCheckerThread;
import server.alarmThreads.PocsagUeberwacher;
import server.config.ServerConfig;
import server.db.SQL;
import server.simon.SimonServer;
import server.util.StdOutErrorLog;


/**
 * @author Christian
 * 
 */
public class AlarmServerMain  {
	
	/**
	 * 
	 */
	private static String version = "2.446";
	
	/**
	 * 
	 */
	private static Logger logger = Logger.getLogger(AlarmServerMain.class);
	
	/**
	 * RMI-Server starten
	 */
	public static void main(String[] args) {

		intLogingAndConfig();
		
		initMysql();
		
		initCaches();	
		
		OnlineCheckerThread.getInstance();
		
		initPocsagUeberwacher();
		
		initRmiServer();
	}
	
	private static void initPocsagUeberwacher() {
		
		Thread t = new Thread(new PocsagUeberwacher());
		t.start();

	}

	private static void initCaches() {
		
		logger.info("Init Caches");
		
		SQL.fillFeuerwehrCache();
		
		logger.info("alle Caches erstellt");
	}

	private static void intLogingAndConfig() {
		
		PropertyConfigurator.configure("log4J.cfg");
		
		StdOutErrorLog.tieSystemOutAndErrToLog();
		
		logger.info("Starte Server! Version: " + version);
		try {
			new ServerConfig("serverConfigLocal.cfg");
			logger.info("Config geladen");
		} catch (IOException e) {
			logger.error("Configfehler", e);
		}
		logger.info("DebugMode: " + ServerConfig.getInstance().isDebug());
		logger.info("Loggen: " + ServerConfig.getInstance().isLoggen());
		
	}
	
	private static void initMysql() {
		boolean sqlConnectionOk = false;
		while(!sqlConnectionOk) {
			try {
				SQL.getInstance();
				logger.info("SQL Verbindung steht");
				sqlConnectionOk = true;
			} catch (Exception e) {
				logger.error("MySQL Fehler " + e.getMessage(), e);
			}
			if(!sqlConnectionOk) {
				logger.info("Warte auf Serververbindung MYSQL");
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
				}
			}
		}
	}
	
	private static void initRmiServer() {
		ServerAlarmAppController controller = new ServerAlarmAppController();
		SimonServer.initServer(controller.getEinsatzList());
		Thread thread = new Thread(controller);
		thread.start();
	}
}
